package com.itheima.agent.controller;

import com.itheima.agent.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class CustomerServiceController {
    
    private  final ChatClient serviceChatClient;

    private final ChatHistoryRepository chatHistoryRepository;
    
    @RequestMapping(value = "/service", produces = "text/html;charset=UTF-8")
    public Flux<String> service(@RequestParam(defaultValue = "讲个笑话") String prompt, String chatId) {
//        1.保存会话id
        chatHistoryRepository.save("service", chatId);
//        2.请求模型
        return serviceChatClient
                .prompt(prompt) // 传入user提示词
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream() // 同步请求,将ai的答案流式返回
                .content(); // 返回相应结果
    }
}
